/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.persistence;

import com.inspur.edp.lcm.metadata.common.Utils;
import com.inspur.edp.lcm.metadata.inner.api.IdeSettingService;
import com.inspur.edp.lcm.metadata.inner.api.data.MavenMirror;
import com.inspur.edp.lcm.metadata.inner.api.utils.IdeSettingUtils;
import java.util.Objects;
import org.apache.maven.model.DeploymentRepository;
import org.apache.maven.model.DistributionManagement;

import java.util.List;

public class MavenSettingsRepository {
    public List<MavenMirror> getRepoUrls() {
        IdeSettingService ideSettingService = IdeSettingUtils.getIdeSettingService();
        if(Objects.isNull(ideSettingService)){
            return null;
        }
        return ideSettingService.getMirrors();
    }

    public String getRepoUrl(String repoId) {
        IdeSettingService ideSettingService = IdeSettingUtils.getIdeSettingService();
        if(Objects.isNull(ideSettingService)){
            return null;
        }
        List<MavenMirror> mirrors =  ideSettingService.getMirrors();
        if (mirrors == null || mirrors.size() <= 0) {
            return null;
        }
        for (MavenMirror mirror : mirrors) {
            if (mirror.getId().equals(repoId)) {
                return mirror.getUrl();
            }
        }
        return null;
    }

    public DistributionManagement getDistributionManagement(String repoId, boolean isSnotshot) {
        DeploymentRepository deploymentRepository = new DeploymentRepository();
        String repoUrl = getRepoUrl(repoId);
        Utils.checkEmpty(repoUrl, "获取仓库地址为空：" + repoId + "，请检查工作空间下的settings.xml文件。");
        deploymentRepository.setId(repoId);
        deploymentRepository.setUrl(repoUrl);

        DistributionManagement distributionManagement = new DistributionManagement();
        if (isSnotshot) {
            distributionManagement.setSnapshotRepository(deploymentRepository);
        } else {
            distributionManagement.setRepository(deploymentRepository);
        }

        return distributionManagement;
    }
}
